package servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ContextServlet2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取ServletContext对象
        ServletContext context2 = getServletContext();
        System.out.println(context2);
        //未设置键值对key1，获得的是null
        System.out.println("保存之前: Context2 获取 key1的值是: " + context2.getAttribute("key1"));
        /*
        * ServletContext是在web工程部署启动的时候创建。在web工程停止的时候销毁
        * */
        //设置key1的值，ServletContext对象直接保存在工程中
        context2.setAttribute("key1", "value1");
        System.out.println("设置值后: Context2 获取 key1的值是: " + context2.getAttribute("key1"));
    }
}
